package com.mdlib.droid.api.callback;


import com.mdlib.droid.AppContext;
import com.mdlib.droid.R;
import com.mdlib.droid.api.BaseResponse;
import com.mdlib.droid.api.exception.ApiException;
import com.mdlib.droid.model.AccountModel;
import com.mdlib.droid.util.core.ToastUtil;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by bin on 17/6/4.
 */

public abstract class BaseCallback<T> extends JsonCallback<T> {

    public abstract void onSucc(T result);


    public void onError(Response response, Exception e) {
        if (e instanceof ApiException) {
            String errMsg = ((ApiException) e).getErrMsg();
            ToastUtil.showToasts(errMsg);
            if (((ApiException) e).getErrCode() == 3000) {
                AccountModel.getInstance().clearCache();
//                UIHelper.goLoginPage(AppContext.getInstance());
            }
        } else {
            ToastUtil.showToasts(AppContext.getInstance().getResources().getString(R.string.network_error));
        }

    }


    @Override
    public void onSuccess(T t, Call call, Response response) {
        if (t instanceof BaseResponse) {
            BaseResponse result = (BaseResponse) t;
            if (result.code == 0) {
                onSucc(t);
            } else {    // 理论上应该不会到这里了
                onError(response, new ApiException(result.code, result.msg));
            }
        }
    }


    @Override
    public void onError(Call call, Response response, Exception e) {
        super.onError(call, response, e);
        onError(response, e);

    }


}
